<template>
  <a-modal
    :title="model && model.id ? '编辑' : '新增'"
    :width="900"
    :height="360"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleOK"
    @cancel="
      () => {
        $emit('cancel')
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item label="id" style="display: none">
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-form-item label="所属店铺">
          <a-select v-decorator="['shopsId', { rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择">
            <a-select-option v-for="item in shopList" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类目名称">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入类目名称' }] }]" />
        </a-form-item>
        <a-form-item label="排序权重">
          <a-input v-decorator="['sortOrder', { rules: [{ required: true, message: '请输入排序权重（数值）' }] }]" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group
            name="radioGroup"
            v-decorator="['state', { rules: [{ required: true, message: '请选择状态' }] }]"
          >
            <a-radio :value="1"> 激活 </a-radio>
            <a-radio :value="2"> 冻结 </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import WangEditor from '@/components/Editor/WangEditor.vue'
import { shopsSelect as select } from '@/api/shop'
// 表单字段
const fields = ['name', 'shopsId', 'id', 'sortOrder', 'state']
export default {
  components: { WangEditor },
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    }
    return {
      form: this.$form.createForm(this),
      shopList: [],
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        this.form.setFieldsValue(pick(this.model, fields))
      }
    })
    this.getShopList()
  },
  methods: {
    handleOK() {
      this.$emit('ok')
    },
    async getShopList() {
      const res = await select()
      if (!res.success) return
      this.shopList = res.data
    },
  },
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
